import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

import path from 'path'
// https://vitejs.dev/config/
export default defineConfig(() => {
  return {
    // 环境变量配置
    define: {
      __DEV__: JSON.stringify(process.env.NODE_ENV === 'development'),
    },
    // 开发服务器配置
    server: {
      port: 3000,        // 固定端口3000
      host: '0.0.0.0',   // 允许外部访问
      open: true,        // 自动打开浏览器
      strictPort: true,  // 端口被占用时不自动尝试下一个端口
      proxy: {
        // API代理到后端
        '/api': {
          target: 'http://localhost:8181',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    // 项目插件
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver({ importStyle: 'css' })],
        dts: false,
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: 'css' })],
        dts: false,
      })
    ],
    // 基础配置
    base: './',
    publicDir: 'public',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            '@border-color-base': '#dce3e8',
          },
          javascriptEnabled: true,
        },
      },
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      assetsInlineLimit: 4096,
      cssCodeSplit: true,
      brotliSize: false,
      sourcemap: false,
      chunkSizeWarningLimit: 1500,
      // 使用默认 esbuild 压缩，构建更快
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('element-plus')) return 'vendor-element-plus'
              if (id.includes('/vue')) return 'vendor-vue'
              if (id.includes('vue-router') || id.includes('pinia')) return 'vendor-router-pinia'
              if (id.includes('axios')) return 'vendor-axios'
              return 'vendor'
            }
          },
        },
      },
    },
  }
})


